package com.aischool.service;

import java.util.ArrayList;
import java.util.List;

import com.aischool.params.AiOrgParams;
import com.aischool.utils.RegexUtil;
import com.aischool.utils.StateEnum;
import com.aischool.utils.StringUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

public class AiOrgService extends BaseService {

	/** 多分类查询示例
	 * SELECT a.* from ai_org a
		INNER JOIN (SELECT regexp_split_to_table(COALESCE('1,2,3',''),E',') AS ids) AS tt 
		ON CAST(tt.ids AS INTEGER) = a.org_id
	 */
	
	
	/**
	 * 获取分页数据
	 * @param params
	 * @return
	 */
	public Page<Record> getPage(AiOrgParams params){
		String sql_select = "SELECT a.*, c.teacher_name ";
		String sql_from   =	"FROM ai_org a "
						  + "LEFT JOIN sys_user b ON b.user_id = a.admin_userid "
						  + "LEFT JOIN ai_teacher c ON c.user_id = a.admin_userid ";
		String sql_where  =	"WHERE a.org_state >= 0 ";
		String sql_order = " ORDER BY a.org_id DESC";
		
		List<Object> listObj = new ArrayList<Object>();
		if (params.getState() != StateEnum.ALL.getState()) {
			sql_where = "WHERE a.org_state = ? ";
			listObj.add(params.getState());
		}
		
		if (StrKit.notBlank(params.getKeywords())) {
			sql_where += this.getLinkWords(sql_where) + " a.org_name LIKE ? ";
			listObj.add("%" + params.getKeywords() + "%");
		}
		return Db.paginate(params.getPageNo(), params.getPageSize(), sql_select, sql_from + sql_where + sql_order, listObj.toArray());
	}
	
	public Record getOrg(int org_id) {
		return Db.findFirst("SELECT a.*, c.teacher_name, c.teacher_mobile "
				+ "FROM ai_org a "
				+ "LEFT JOIN sys_user b ON b.user_id = a.admin_userid "  
				+ "LEFT JOIN ai_teacher c ON c.user_id = a.admin_userid " +
				"WHERE a.org_id = ?", org_id);
	}

	public Record getOrg(String family_code, String teacher_code) {
		String sql = "SELECT a.* "
				+ "FROM ai_org a "
				+ "WHERE ";
		List<String> listparams = new ArrayList<String>();
		if (StrKit.notBlank(family_code)) {
			sql += " a.family_code = ? ";
			listparams.add(family_code);
		}
		if (StrKit.notBlank(teacher_code)) {
			if (sql.indexOf("family_code") > 0) {
				sql += " OR ";
			}
			sql += " a.teacher_code = ? ";
			listparams.add(teacher_code);
		}
		return Db.findFirst(sql, listparams.toArray());
	}
	
	public boolean del(int org_id) {
		int ir = Db.delete("DELETE FROM ai_org WHERE org_id = ?", org_id);
		return ir > 0;
	}
	
	public boolean delMore(String ids) {
		if (StrKit.isBlank(ids)) {
			return false;
		}
		if (RegexUtil.isSqlIds(ids)) {
			int ir = Db.delete("DELETE FROM ai_org WHERE org_id IN("+StringUtil.trim(ids, ',')+")");
			return ir > 0;
		}
		
		return false;
	}
}
